<template>
    <button :class="{ 'back-to-top-button': true, 'visible': isVisible }" @click="scrollToTop">
        <svg class="icon" aria-hidden="true" style="">
            <use xlink:href="#icon-huojian"></use>
        </svg>
    </button>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { UpOutlined } from '@ant-design/icons-vue';

const props = defineProps({
    threshold: {
        type: Number,
        default: 300
    },
    duration: {
        type: Number,
        default: 500
    }
});

const isVisible = ref(false);

const handleScroll = () => {
    isVisible.value = window.scrollY > props.threshold;
};

const scrollToTop = () => {
    const start = window.scrollY;
    const startTime = performance.now();

    const scrollStep = (timestamp) => {
        const elapsedTime = timestamp - startTime;
        const progress = Math.min(elapsedTime / props.duration, 1);
        const easeOutQuart = (t) => 1 - Math.pow(1 - t, 4);
        const easeProgress = easeOutQuart(progress);

        window.scrollTo(0, start - start * easeProgress);

        if (progress < 1) {
            window.requestAnimationFrame(scrollStep);
        }
    };

    window.requestAnimationFrame(scrollStep);
};

onMounted(() => {
    window.addEventListener('scroll', handleScroll);
    handleScroll();
});

onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
});

watch(() => props.threshold, handleScroll);
</script>

<style scoped>
.back-to-top-button {
    font-size: 50px;
    background-color: transparent;
    position: fixed;
    bottom: 24px;
    right: 10px;
    z-index: 99999999;
    border: none;
    border-radius: 50%;
    /* 修复为白色文字 */
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    opacity: 0;
    transform: translateY(20px);
    transition: opacity 0.3s ease, transform 0.3s ease;
}

.back-to-top-button.visible {
    opacity: 1;
    transform: translateY(0);
}

.back-to-top-button:hover {
    transform: scale(1.1);
    transition: all 0.3s ease;
}

.back-to-top-button:focus {
    outline: none;
}
</style>